package com.learn.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 编译结果
 * Thread 1 read value :1
 * Thread 2 read value : 1
 * Thread 2 update from : 1 to 2
 * Thread 2 update from : 2 to 1
 * Thread 1 update from :1 to 3
 *
 * 会导致Thread 1 获取到的1并不是真正一致的，这就是ABA问题
 *
 */
public class AtomicIntegerABA {

    public static void main(String[] args) {
        AtomicInteger atom = new AtomicInteger(1);
        new Thread(()->{
            int value = atom.get();
            System.out.println("Thread 1 read value :" + value);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (atom.compareAndSet(value,3)) {
                int i = atom.get();
                System.out.println("Thread 1 update from :" + value + " to "+ i);
            }else{
                System.out.println("Thread 1 update failed");
            }
        }).start();


        new Thread(()->{
            int value = atom.get();
            System.out.println("Thread 2 read value : "+ value);
            if (atom.compareAndSet(value,2)) {
                int v1 = atom.get();
                System.out.println("Thread 2 update from : "+ value + " to " + v1);

                if (atom.compareAndSet(v1,1)) {
                    System.out.println("Thread 2 update from : "+ v1 + " to " + atom.get());
                }
            }
        }).start();
    }
}
